package com.qianlou.controller;


import com.qianlou.common.enums.ResponseStatusEnum;
import com.qianlou.common.result.BaseResponse;
import com.qianlou.config.MinIOConfig;
import com.qianlou.common.utils.MinIOUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController()
@RequestMapping("/file")
public class FileController {

    @Resource
    private MinIOConfig minioConfig;

    @Resource
    private MinIOUtils minIOUtils;

    @PostMapping("/uploadInterviewerImage")
    public BaseResponse uploadInterviewerImage(@RequestParam("file")MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)) {
            return BaseResponse.errorMsg(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR.msg());
        }
        filename = "interviewer/" + dealWithFilename(filename);
        String imageUrl = minIOUtils.uploadFile(minioConfig.getBucketName(), filename, file.getInputStream(), true);
        return BaseResponse.ok(imageUrl);
    }

    @PostMapping("/uploadInterviewVideo")
    public BaseResponse uploadInterviewVideo(@RequestParam("file")MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)) {
            return BaseResponse.errorMsg(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR.msg());
        }
        filename = "interviewVideo/" + dealWithFilename(filename);
        String imageUrl = minIOUtils.uploadFile(minioConfig.getBucketName(), filename, file.getInputStream(), true);
        return BaseResponse.ok(imageUrl);
    }


    private String dealWithFilename(String filename) {
        String suffixName = getSuffixOfFile(filename);
        String prefixName = filename.substring(0, filename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replace("-", "");
        return prefixName + "-" + uuid + suffixName;
    }
    private String dealWithoutFilename(String filename) {
        String suffixName = getSuffixOfFile(filename);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        return  uuid + suffixName;
    }
    private String getSuffixOfFile(String fileName) {
        int suffixIndex = fileName.lastIndexOf(".");
        return suffixIndex == -1 ? "" : fileName.substring(suffixIndex);
    }
}
